package a05_双指针法;

import java.util.Arrays;

/**
 * <p>
 * a04_翻转字符串里的单词复习4
 * </p>
 *
 * @author flyduck
 * @since 2025/2/18
 */
public class a04_翻转字符串里的单词复习4 {

    public static void main(String[] args) {
        a04_翻转字符串里的单词复习4 tes = new a04_翻转字符串里的单词复习4();
        System.out.println(tes.reverseWords(" a  is  good sample  "));
    }

    // a  is  good sample
    public String reverseWords(String s) {
        char[] oldChars = s.toCharArray();
        //去除空格
        char[] newChars = removeAllSpaces(oldChars);

        //反转全部
        reverse(newChars,0,newChars.length-1);

        //反转每一个单词
        reverseEachWord(newChars);

        return new String(newChars);
    }

    private void reverseEachWord(char[] newChars) {
        int leftIdx = 0;
        int rightIdx = 0;
        while (rightIdx < newChars.length) {
            if(rightIdx == newChars.length - 1 || newChars[rightIdx+1] == ' '){
                reverse(newChars,leftIdx,rightIdx);
                rightIdx = rightIdx + 2;
                leftIdx = rightIdx;
            }else {
                rightIdx++;
            }
        }
    }

    private void reverse(char[] newChars, int leftIdx, int rightIdx) {
        while (leftIdx < rightIdx){
            char temp = newChars[leftIdx];
            newChars[leftIdx] = newChars[rightIdx];
            newChars[rightIdx] = temp;
            leftIdx++;
            rightIdx--;
        }
    }

    private char[] removeAllSpaces(char[] oldChars) {
        int slowIdx = 0;
        int fastIdx = 0;
        while (fastIdx < oldChars.length){
            if(oldChars[fastIdx] != ' '){
                if(slowIdx != 0){
                    oldChars[slowIdx] = ' ';
                    slowIdx++;
                }

                while(fastIdx < oldChars.length && oldChars[fastIdx] != ' '){
                    oldChars[slowIdx] = oldChars[fastIdx];
                    fastIdx++;
                    slowIdx++;
                }
            }else {
                fastIdx++;
            }
        }
        return  Arrays.copyOfRange(oldChars, 0, slowIdx);
    }


}
